"use client"

import type React from "react"

import { useState, useRef, useEffect } from "react"
import { Participant } from "@/lib/types"

type LayoutElement = {
  id: string
  x: number
  y: number
  width: number
  height: number
  zIndex: number
  label: string
  participantId?: string
}

type LayoutPreviewProps = {
  elements: LayoutElement[]
  canvasSize: { width: number; height: number }
  selectedElement: string | null
  setSelectedElement: (id: string | null) => void
  updateElement: (id: string, updates: Partial<LayoutElement>) => void
  participants: Participant[]
  assignParticipant: (elementId: string, participantId: string) => void
  removeParticipant: (elementId: string) => void
}

export function LayoutPreview({
  elements,
  canvasSize,
  selectedElement,
  setSelectedElement,
  updateElement,
  participants,
  assignParticipant,
  removeParticipant,
}: LayoutPreviewProps) {
  const containerRef = useRef<HTMLDivElement>(null)
  const [scale, setScale] = useState(1)
  const [dragging, setDragging] = useState<string | null>(null)
  const [resizing, setResizing] = useState<string | null>(null)
  const [resizeDirection, setResizeDirection] = useState<string | null>(null)
  const [startPos, setStartPos] = useState({ x: 0, y: 0 })
  const [elementStartPos, setElementStartPos] = useState({ x: 0, y: 0, width: 0, height: 0 })

  // 计算缩放比例以适应容器
  useEffect(() => {
    const updateScale = () => {
      if (containerRef.current) {
        const containerWidth = containerRef.current.clientWidth
        const scaleValue = containerWidth / canvasSize.width
        setScale(scaleValue)
      }
    }

    updateScale()
    window.addEventListener("resize", updateScale)
    return () => window.removeEventListener("resize", updateScale)
  }, [canvasSize.width])

  // 处理元素拖动开始
  const handleDragStart = (id: string, e: React.MouseEvent) => {
    e.preventDefault()
    const element = elements.find((el) => el.id === id)
    if (!element) return

    setDragging(id)
    setSelectedElement(id)
    setStartPos({ x: e.clientX, y: e.clientY })
    setElementStartPos({
      x: element.x,
      y: element.y,
      width: element.width,
      height: element.height,
    })

    // 添加全局鼠标事件监听
    document.addEventListener("mousemove", handleDragMove)
    document.addEventListener("mouseup", handleDragEnd)
  }

  // 处理元素拖动
  const handleDragMove = (e: MouseEvent) => {
    if (!dragging) return

    const deltaX = (e.clientX - startPos.x) / scale
    const deltaY = (e.clientY - startPos.y) / scale

    updateElement(dragging, {
      x: Math.max(0, Math.min(canvasSize.width - elementStartPos.width, elementStartPos.x + deltaX)),
      y: Math.max(0, Math.min(canvasSize.height - elementStartPos.height, elementStartPos.y + deltaY)),
    })
  }

  // 处理元素拖动结束
  const handleDragEnd = () => {
    setDragging(null)

    // 移除全局鼠标事件监听
    document.removeEventListener("mousemove", handleDragMove)
    document.removeEventListener("mouseup", handleDragEnd)
  }

  // 处理调整大小开始
  const handleResizeStart = (id: string, direction: string, e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()

    const element = elements.find((el) => el.id === id)
    if (!element) return

    setResizing(id)
    setResizeDirection(direction)
    setSelectedElement(id)
    setStartPos({ x: e.clientX, y: e.clientY })
    setElementStartPos({
      x: element.x,
      y: element.y,
      width: element.width,
      height: element.height,
    })

    // 添加全局鼠标事件监听
    document.addEventListener("mousemove", handleResizeMove)
    document.addEventListener("mouseup", handleResizeEnd)
  }

  // 处理调整大小
  const handleResizeMove = (e: MouseEvent) => {
    if (!resizing || !resizeDirection) return

    const deltaX = (e.clientX - startPos.x) / scale
    const deltaY = (e.clientY - startPos.y) / scale

    const updates: Partial<LayoutElement> = {}

    // 根据调整方向更新元素属性
    if (resizeDirection.includes("n")) {
      updates.y = Math.min(elementStartPos.y + elementStartPos.height - 50, elementStartPos.y + deltaY)
      updates.height = Math.max(50, elementStartPos.height - deltaY)
    }

    if (resizeDirection.includes("s")) {
      updates.height = Math.max(50, elementStartPos.height + deltaY)
    }

    if (resizeDirection.includes("w")) {
      updates.x = Math.min(elementStartPos.x + elementStartPos.width - 50, elementStartPos.x + deltaX)
      updates.width = Math.max(50, elementStartPos.width - deltaX)
    }

    if (resizeDirection.includes("e")) {
      updates.width = Math.max(50, elementStartPos.width + deltaX)
    }

    updateElement(resizing, updates)
  }

  // 处理调整大小结束
  const handleResizeEnd = () => {
    setResizing(null)
    setResizeDirection(null)

    // 移除全局鼠标事件监听
    document.removeEventListener("mousemove", handleResizeMove)
    document.removeEventListener("mouseup", handleResizeEnd)
  }

  // 处理拖拽进入
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    e.dataTransfer.dropEffect = "copy"
  }

  // 处理拖拽放置
  const handleDrop = (e: React.DragEvent, elementId: string) => {
    e.preventDefault()
    e.stopPropagation()

    try {
      const data = JSON.parse(e.dataTransfer.getData("application/json"))
      if (data.type === "participant") {
        assignParticipant(elementId, data.participantId)
      }
    } catch (error) {
      console.error("Invalid drag data:", error)
    }
  }

  return (
    <div
      ref={containerRef}
      className="relative border border-gray-300 overflow-hidden"
      style={{
        width: "100%",
        height: canvasSize.height * scale,
        background:
          "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 20 20'%3E%3Cpath d='M1,1 L19,1 L19,19 L1,19 L1,1 Z' fill='none' stroke='%23eee' strokeWidth='0.5'/%3E%3C/svg%3E\") repeat",
      }}
    >
      <div
        className="absolute top-0 left-0 origin-top-left"
        style={{
          width: canvasSize.width,
          height: canvasSize.height,
          transform: `scale(${scale})`,
          transformOrigin: "top left",
        }}
      >
        {elements.map((element) => {
          const participant = participants.find(p => p.id === element.participantId);

          return (
            <div
              key={element.id}
              className={`absolute border-2 ${
                selectedElement === element.id ? "border-blue-500" : "border-gray-400"
              } bg-gray-100 bg-opacity-50 cursor-move`}
              style={{
                left: element.x,
                top: element.y,
                width: element.width,
                height: element.height,
                zIndex: element.zIndex,
              }}
              onClick={(e) => {
                e.stopPropagation()
                setSelectedElement(element.id)
              }}
              onMouseDown={(e) => handleDragStart(element.id, e)}
              onDragOver={handleDragOver}
              onDrop={(e) => handleDrop(e, element.id)}
            >
              <div className="absolute inset-0 flex flex-col items-center justify-center p-2">
                <div className="text-sm font-medium text-gray-700 pointer-events-none">
                  {element.label}
                </div>

                {participant && (
                  <div className="mt-1 flex items-center gap-1">
                    <div className="text-xs px-2 py-0.5 bg-blue-100 text-blue-700 rounded-full">
                      {participant.name}
                    </div>
                    {selectedElement === element.id && (
                      <button
                        className="text-xs text-red-500 hover:text-red-700 ml-1"
                        onClick={(e) => {
                          e.stopPropagation();
                          removeParticipant(element.id);
                        }}
                      >
                        ×
                      </button>
                    )}
                  </div>
                )}
              </div>

            {selectedElement === element.id && (
              <>
                {/* 调整大小的手柄 */}
                <div
                  className="absolute top-0 left-0 w-3 h-3 bg-blue-500 rounded-full cursor-nw-resize -translate-x-1/2 -translate-y-1/2"
                  onMouseDown={(e) => handleResizeStart(element.id, "nw", e)}
                />
                <div
                  className="absolute top-0 right-0 w-3 h-3 bg-blue-500 rounded-full cursor-ne-resize translate-x-1/2 -translate-y-1/2"
                  onMouseDown={(e) => handleResizeStart(element.id, "ne", e)}
                />
                <div
                  className="absolute bottom-0 left-0 w-3 h-3 bg-blue-500 rounded-full cursor-sw-resize -translate-x-1/2 translate-y-1/2"
                  onMouseDown={(e) => handleResizeStart(element.id, "sw", e)}
                />
                <div
                  className="absolute bottom-0 right-0 w-3 h-3 bg-blue-500 rounded-full cursor-se-resize translate-x-1/2 translate-y-1/2"
                  onMouseDown={(e) => handleResizeStart(element.id, "se", e)}
                />
                <div
                  className="absolute top-0 left-1/2 w-3 h-3 bg-blue-500 rounded-full cursor-n-resize -translate-x-1/2 -translate-y-1/2"
                  onMouseDown={(e) => handleResizeStart(element.id, "n", e)}
                />
                <div
                  className="absolute bottom-0 left-1/2 w-3 h-3 bg-blue-500 rounded-full cursor-s-resize -translate-x-1/2 translate-y-1/2"
                  onMouseDown={(e) => handleResizeStart(element.id, "s", e)}
                />
                <div
                  className="absolute left-0 top-1/2 w-3 h-3 bg-blue-500 rounded-full cursor-w-resize -translate-x-1/2 -translate-y-1/2"
                  onMouseDown={(e) => handleResizeStart(element.id, "w", e)}
                />
                <div
                  className="absolute right-0 top-1/2 w-3 h-3 bg-blue-500 rounded-full cursor-e-resize translate-x-1/2 -translate-y-1/2"
                  onMouseDown={(e) => handleResizeStart(element.id, "e", e)}
                />
              </>
            )}
          </div>)
          })
        }
      </div>
      </div>)

}
